package com.hot12345.database;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.hot12345.server.DBConnection.TianyaDBConnectionProvider;

/**
 * 获取数据库数据类
 * <p>Title: </p>
 * 
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2005</p>
 *
 * <p>Company: </p>
 *
 * @author not attributable
 * @version 1.0
 */

public class DBDataProvider {
	private static Log logger = LogFactory.getLog(DBDataProvider.class);
 
    public List getMapFromDB(String dbID, String sql,Object[] params) throws Exception {
        List list = new ArrayList(1);
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        PreparedStatement ps=null;
        try {
        	// System.out.println("数据库ID...."+dbID);
        	con = TianyaDBConnectionProvider.getConnection(dbID.trim());
        }catch(Exception ex){
        	throw new Exception(ex);
        }
            /************************/ 
 try {
            ps = con.prepareStatement(sql);
  	      int index = 1;
  	      if (params != null) {
  	        int n = params.length;
  	        if (n < 2 || n % 2 != 0 || (n/2)!=this.getStrNum(sql,"?")) {
  	          throw new IllegalArgumentException(
  	              "����Ϊ���������С��2,�����ǲ���ĸ���һ��");
  	        }
  	        for (int i = 0; i < params.length; i += 2) {
  	          params[i+1]=this.pareObjToStr(params[i+1]);//�ѵڶ����������ת��Ϊ�ַ�����
  	          if ( ( (String) params[i]).toLowerCase().equals("string")) {
  	            ps.setString(index++, (String) params[i + 1]);
  	          }
  	          if ( ( (String) params[i]).toLowerCase().equals("long")) {
  	            ps.setLong(index++, Long.parseLong( (String) params[i + 1]));
  	          }
  	          if ( ( (String) params[i]).toLowerCase().equals("int")) {
  	            ps.setInt(index++, Integer.parseInt( (String) params[i + 1]));
  	          }
  	          if ( ( (String) params[i]).toLowerCase().equals("date")) {
  	            ps.setString(index++, (String) params[i + 1]);
  	          }
  	          if ( ( (String) params[i]).toLowerCase().equals("float")) {
  	           ps.setFloat(index++, Float.parseFloat((String) params[i + 1]));
  	         }
  	         if ( ( (String) params[i]).toLowerCase().equals("double")) {
  	           ps.setDouble(index++, Double.parseDouble((String) params[i + 1]));
  	         }

  	          if ( ( (String) params[i]).toLowerCase().equals("image")) {
  	            ps.setBytes(index++, (byte[]) params[i + 1]);

  	          }
  	        }
  	      }
  	      rs = ps.executeQuery();
  	    
         /********************/
            ResultSetMetaData rsmd = rs.getMetaData();
            int count=rsmd.getColumnCount();
            ArrayList nameList = new ArrayList();
            for (int i = 1; i <= count; i++) { // JDBC is one-relative!
                String name = rsmd.getColumnName(i).toLowerCase();
               // System.out.println(" 列名"+name);
                nameList.add(name);
            }              
            while (rs.next()) {
                Map map = new HashMap();
                for (int i = 0; i <count ; i++) {                
                    map.put((String) nameList.get(i), rs.getObject(i+1));
                }
                list.add(map);  
            }
        } catch (SQLException ex) {
        	throw ex;
                  
        } finally {
            try { 
                if (rs != null) {
                    rs.close();
                }
                if (stmt != null) {
                    stmt.close();
                }
                if (con != null) {
                    con.close();
                }

            } catch (Exception e) {
                logger.error("Exception",e);
            }
        }
        return list;
    }
    
      
	  
	  /**
	   *ͳ��ԭ�����ַ��а��ʵ���ַ�ĸ���
	   * @param sql ԭ�����ַ�
	   * @param str ���а���ַ�
	   * @return ԭ�ַ�Ӵ��а���ַ�ĸ���
	   */
	  private int getStrNum(String sql,String str) {
	    int num = 0;
	    int index = sql.indexOf(str);
	    while (index != -1) {
	      num++;
	      index=sql.indexOf(str,index+str.length());
	    }
	    return num;
	  }
	  
	  
	  /**
	   * ��Object���Ͷ�������Ӧ�����ͽ���ת��������String����
	   * @param obj
	   * @return ����String����
	   */
	  private String pareObjToStr(Object obj){
	    if(obj==null)
	      return null;
	    if(obj instanceof String)
	      return obj.toString();
	    if(obj instanceof Integer)
	      return ((Integer)obj).toString();
	    if(obj instanceof Long)
	      return ((Long)obj).toString();
	    if(obj instanceof Float)
	      return ((Float)obj).toString();
	    if(obj instanceof Double)
	      return ((Double)obj).toString();
	    if(obj instanceof java.util.Date)
	      return new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((java.util.Date)obj);

	    return obj.toString();
	  }
}
